﻿using MicroConfig.NetCore.Server.Services;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MicroConfig.NetCore.Server
{
    public class MicroConfigHub : Hub
    {


        public async Task RegisterProject(string projectName)
        {
            this.Context.GetHttpContext().Request.Cookies.TryGetValue("x-token", out string token);
            var project = ProjectService.Instance.CacheList.FirstOrDefault(x => x.Name.Equals(projectName, StringComparison.OrdinalIgnoreCase));
            if (project != null && project.Token.Equals(token, StringComparison.OrdinalIgnoreCase))
            {
                await Groups.AddToGroupAsync(Context.ConnectionId, project.Id.ToString());
                Dictionary<string, Dictionary<string, string>> items = new Dictionary<string, Dictionary<string, string>>();

                foreach (var gp in ConfigItemService.Instance.CacheList.Where(x => x.ProjectId == project.Id).GroupBy(x => x.Key))
                {
                    var data = new Dictionary<string, string>();
                    foreach (var item in gp)
                    {
                        data.Add(item.Environment, item.Value);
                    }
                    items.Add(gp.Key, data);
                }
                await Clients.Caller.SendAsync("SyncItems", items);
            }
        }


        public override Task OnDisconnectedAsync(Exception exception)
        {
            return base.OnDisconnectedAsync(exception);
        }
        public override Task OnConnectedAsync()
        {
            this.Context.GetHttpContext().Request.Cookies.TryGetValue("x-token", out string token);
            //验证token是否在Project里
            if (ProjectService.Instance.CacheList.Any(x => x.Token.Equals(token, StringComparison.OrdinalIgnoreCase)))
            {
                return base.OnConnectedAsync();
            }
            else
            {
                Context.Abort();
                return Task.CompletedTask;
            }
        }
    }
}
